<template>
  <el-dialog
    class="formdrawer"
    :title="form.uId ? $t('user.Editemployee') : $t('user.Newemployee')"
    v-model="visible"
  >
    <!--  表单内容 -->
    <el-form
      class="formstyle"
      :model="form"
      ref="dataFormRef"
      :rules="rules"
      label-position="right"
      label-width="120px"
      @submit.prevent
    >
      <el-form-item :label="$t('user.Userid')" prop="uId">
        <el-input v-model="form.uId" :style="{ width: '500px' }" disabled />
      </el-form-item>
      <el-form-item :label="$t('user.username')" prop="uName">
        <el-input v-model="form.uName" :style="{ width: '500px' }" />
      </el-form-item>
      <el-form-item :label="$t('user.password')" prop="uPwd">
        <el-input v-model="form.uPwd" :style="{ width: '500px' }" />
      </el-form-item>
      <el-form-item :label="$t('user.telephone')" prop="uPhone">
        <el-input
          v-model="form.uPhone"
          type="number"
          :style="{ width: '500px' }"
        />
      </el-form-item>
      <el-form-item :label="$t('user.mailbox')" prop="uEMail">
        <el-input v-model="form.uEMail" :style="{ width: '500px' }" />
      </el-form-item>
      <el-form-item :label="$t('user.age')" prop="uAge">
        <el-input
          v-model="form.uAge"
          :style="{ width: '500px' }"
          type="number"
        />
      </el-form-item>
      <el-form-item :label="$t('user.role')" prop="uRole">
        <el-radio-group v-model="form.uRole">
          <span
            style="margin-right: 20px"
            v-for="item in roleArr"
            :key="item.uRole"
          >
            <el-radio :label="item.uRole" @click="uRoleNameBtn(item.uRoleName)"
              >{{ item.uRoleName }}--{{ item.uRole }}
            </el-radio>
          </span>
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="$t('entirety.status')" prop="uStage">
        <el-radio-group v-model="form.uStage">
          <el-radio :label="1"> {{ $t("entirety.enable") }}</el-radio>
          <el-radio :label="0"> {{ $t("entirety.forbidden") }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="$t('user.sex')" prop="uSex">
        <el-radio-group v-model="form.uSex">
          <el-radio :label="'1'"> {{ $t("user.man") }}</el-radio>
          <el-radio :label="'0'">{{ $t("user.woman") }}</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>

    <!-- 底部的确认、取消按钮 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancleBtn">{{ $t("entirety.Cancel") }}</el-button>
        <el-button type="primary" @click="onSubmit" :disabled="loading">
          {{ $t("entirety.OK") }}
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  apiAddUser,
  apiPutUserInfo,
  apiGetUser,
  apiAllRoleUser,
} from "@/api/user";
import emitter from "@/utils/eventbus"; //引入bus

// 定义变量内容
const visible = ref(false);
const loading = ref(false);
const dataFormRef = ref(); // form表单的ref
const roleArr = ref(); //角色数组

// 提交表单数据
const form = reactive({
  uId: "",
  uRole: "",
  uRoleName: "",
  uEMail: "",
  uPwd: "123",
  uName: "",
  uPhone: "",
  uStage: 1,
  uSex: "1",
  uAge: "",
  uAccount: "",
  uPower: "",
  userRole: [
    {
      uRole: "",
      uRoleName: "",
    },
  ],
  userRolePower: [
    {
      uRole: "",
    },
  ],
});
// 清空表单
const clearForm = () => {
  form.uId = "";
  form.uRole = "";
  form.uRoleName = "";
  form.uEMail = "";
  form.uPwd = "123";
  form.uName = "";
  form.uPhone = "";
  form.uStage = 1;
  form.uSex = "1";
  form.uAge = "";
  form.uAccount = "";
  form.uPower = "";
  form.userRole = [
    {
      uRole: "",
      uRoleName: "",
    },
  ];
  form.userRolePower = [
    {
      uRole: "",
    },
  ];
};
// 校验规则
const rules = {
  uEMail: [
    {
      required: true,
      message: "邮箱不可为空",
    },
    {
      pattern: /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/,
      message: "请输入有效的邮箱地址",
    },
  ],
  uName: [
    {
      required: true,
      message: "用户名不可为空",
    },
    // {
    //   min: 2,
    //   max: 5,
    //   message: "用户名长度必须在2到5之间",
    // },
  ],
  uPhone: [
    {
      required: true,
      message: "电话不可为空",
    },
    {
      pattern: /^[1][3,4,5,7,8,9][0-9]{9}$/,
      message: "电话格式不正确",
    },
  ],
  uPwd: [
    {
      required: true,
      message: "密码不可为空",
    },
  ],
  uSex: [
    {
      required: true,
      message: "性别不可为空",
    },
  ],
  uAge: [
    {
      required: true,
      message: "年龄不可为空",
    },
  ],
  uRole: [
    {
      required: true,
      message: "角色不可为空",
    },
  ],
  uStage: [
    {
      required: true,
      message: "状态不可为空",
    },
  ],
};

// 打开弹窗
const openDialog = async (tempId: string, row: any) => {
  visible.value = true; // 打开弹窗
  form.uId = ""; // 防止上次的操作还在表单上，影响本次操作
  // 重置表单数据---否则新增弹窗会自动触发校验
  nextTick(() => {
    dataFormRef.value?.resetFields();
  });

  await apiAllRoleUser() //获取所有角色信息
    .then((res) => {
      roleArr.value = res;
    });

  // 获取信息
  if (tempId) {
    // 如果有id，就编辑逻辑
    form.uId = tempId;
    await Object.assign(form, row);
  } else {
    // 添加逻辑
    clearForm(); //清空表单
  }
};
//
const uRoleNameBtn = (name: string) => {
  form.uRoleName = name;
};

// 提交表单
const onSubmit = async () => {
  // 表单校验
  const valid = await dataFormRef.value.validate().catch(() => {});
  if (!valid) return false;
  form.uPower = form.uRole;
  form.userRole[0].uRole = form.uRole;
  form.userRole[0].uRoleName = form.uRoleName;
  form.userRolePower[0].uRole = form.uRole;

  try {
    loading.value = true;
    // 如果有id，就修改接口，否则新增接口
    form.uId
      ? await apiPutUserInfo([form])
          .then((res: any) => {
            if (res.code == 200) {
              // 提示框
              ElMessage({
                message: "修改成功",
                type: "success",
              });
            } else {
              ElMessage({
                message: res.msg,
                type: "error",
              });
            }
          })
          .catch((err) => {
            ElMessage.error(err.message);
          })
      : await apiAddUser([{ ...form, uId: form.uName }])
          .then((res: any) => {
            if (res.code == 200) {
              // 提示框
              ElMessage({
                message: "新增成功",
                type: "success",
              });
            } else {
              ElMessage({
                message: res.msg,
                type: "error",
              });
            }
          })
          .catch((err) => {
            ElMessage.error(err.message);
          });
    visible.value = false;
    emitter.emit("refreshUser"); //调用父组件刷新方法
  } catch (err: any) {
    ElMessage.error(err.msg);
  } finally {
    loading.value = false;
  }
};

// 取消按钮
const cancleBtn = () => {
  visible.value = false;
};

// 暴露变量
defineExpose({
  openDialog,
});
</script>

<style scoped lang="scss">
.formstyle {
  padding: 0 80px;
}
</style>
